package com.example.mlm;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.example.pojos.Product;
import com.example.pojos.Product_Type;
import com.example.tools.myCustomView;

public class AfficheProduit extends ListActivity implements OnItemClickListener{
	private ArrayList<Product> products;
	private ListView listView;
	private myCustomView customAdapter;
	private boolean isPanier;
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Intent intent = getIntent();
		
		if(products==null){
			isPanier = (Boolean)intent.getExtras().get("isPanier");
			if(isPanier){
				read_pan();
			}else{
				products = (ArrayList<Product>) intent.getExtras().get("products");
			}
		}

		customAdapter = new myCustomView(this, R.layout.my_affiche_product2, products);
        setListAdapter(customAdapter);
        
        listView = getListView();
        listView.setOnItemClickListener(this);
        registerForContextMenu(listView);
	}
	
	@Override
	public void setListAdapter(ListAdapter adapter) {
		super.setListAdapter(adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_affiche_produit, menu);
		return true;
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	    super.onCreateContextMenu(menu, v, menuInfo);
	    MenuInflater inflater = getMenuInflater();
	    if(!isPanier)
	    	inflater.inflate(R.menu.activity_affiche_produit_long_click, menu);
	    else
	    	inflater.inflate(R.menu.activity_affiche_produit_long_click_pan, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    int pos;
	    switch (item.getItemId()) {
	        case R.id.add_product:
	            pos = info.position;
	            modify_pan(pos, false);
	            return true;
	        case R.id.remove_product:
	        	pos = info.position;
	        	modify_pan(pos, true);
	        default:
	            return super.onContextItemSelected(item);
	    }
	}
	
	@SuppressWarnings("unchecked")
	public void read_pan(){
		try {
            FileInputStream fStream = openFileInput("panier.bin") ;
            ObjectInputStream oStream = new ObjectInputStream(fStream);

            products = (ArrayList<Product>) oStream.readObject();        
            oStream.close();

            Log.e("deSerialization success", "Success panier");
        } catch (Exception e) {
        	products = new ArrayList<Product>();
            Log.e("IO Exception", e.getMessage());
        }
	}
	
	@SuppressWarnings("unchecked")
	public void modify_pan(int position, boolean remove){
		List<Product> panier;
		try {
            FileInputStream fStream = openFileInput("panier.bin") ;
            ObjectInputStream oStream = new ObjectInputStream(fStream);

            panier = (List<Product>) oStream.readObject();        
            oStream.close();

            Log.e("deSerialization success", "Success panier");
        } catch (Exception e) {
        	panier = new ArrayList<Product>();
            Log.e("IO Exception", e.getMessage());
        }
		if(!remove){
			if(!panier.contains(products.get(position)))
				panier.add(products.get(position));
		}
		else{
			panier.remove(position);
			products.remove(position);
		}
        try {
            FileOutputStream fStream = openFileOutput("panier.bin", Context.MODE_PRIVATE) ;
            ObjectOutputStream oStream = new ObjectOutputStream(fStream);

            oStream.writeObject(panier);        
            oStream.flush();
            oStream.close();

            Log.e("Serialization success", "Success panier");
        } catch (Exception e) {
            Log.e("IO Exception", e.getMessage());
        }
        
        if(remove){
        	Log.e("remove", "enleve de la liste");
        	customAdapter.notifyDataSetChanged();
        	//customAdapter.notifyDataSetInvalidated();
        	//listView.invalidate();
        }
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.Tri_par_nom:
	            Collections.sort(products, Product.COMPARE_BY_PRODUCTNAME);
	            customAdapter.notifyDataSetChanged();
	            return true;
	        case R.id.Tri_par_prix:
	            Collections.sort(products, Product.COMPARE_BY_PRODUCTPRICE);
	            customAdapter.notifyDataSetChanged();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}

	/*@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int pos, long id) {
		
		return true;
	}*/
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
		Intent intent = null;
		Product_Type cat = products.get(position).getCategorie();
		switch (cat) {
			case VIDEO:
				intent = new Intent(this, Detail_video.class);
				break;
			case IMAGE:
				intent = new Intent(this, Detail_image.class);
				break;
			case DEVICE:
				intent = new Intent(this, Detail_image.class);
				break;
			case MUSIQUE:
				intent = new Intent(this, Detail_musique.class);
				break;
		}
		  intent.putExtra("product", (Parcelable)products.get(position));
		  startActivity(intent);
	} 
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putParcelableArrayList("products", products);
	}
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		products = savedInstanceState.getParcelableArrayList("products");
	}

}
